#include "CsvParser.h"
#include "common/common.h"


CsvParser::CsvParser(void)
{
	m_nRow=0;
	m_nCol=0;
}


CsvParser::~CsvParser(void)
{
}

bool CsvParser::openFile( const char* pszPash )
{
	string strPash = CCFileUtils::fullPathFromRelativePath(pszPash);
	unsigned long nBufLen=0;
	unsigned char* pBuff = CCFileUtils::getFileData(strPash.c_str(), "r", &nBufLen);


	string str = (char*)pBuff;

	vector<string> line;
	StringSplit(str, line, '\n'); 
	for (unsigned int i=0 ; i<line.size(); i++)
	{
		vector<string> field;
		StringSplit(line[i], field, ','); 
		m_nCol =max(m_nCol, field.size());
		m_vData.push_back(field);  
	}
	m_nRow=line.size();
	return true;
}

void CsvParser::StringSplit( const string& str, vector<string>& tokens, const char& delimiters )
{
	string::size_type posLast = str.find_first_not_of(delimiters,0);
	string::size_type pos = str.find_first_of(delimiters, posLast);

	while (posLast!= string::npos || string::npos != pos)
	{
		tokens.push_back(str.substr(posLast, pos-posLast));

		posLast = str.find_first_not_of(delimiters, pos);
		pos = str.find_first_of(delimiters, posLast);
	}
}

const char* CsvParser::getData( unsigned int nRow, unsigned int nCol )
{
	if (nRow > m_nRow || m_vData[nRow].size() <= nCol)
	{
		return "";
	}
	return m_vData[nRow][nCol].c_str();

}
